package com.whfc.wxmp.api.sys.service.impl;

import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.service.AppEmpService;
import com.whfc.emp.service.FileUploadInfoService;
import com.whfc.emp.entity.FileUploadInfo;
import com.whfc.entity.dto.Apply.rep.FileUploadInfoRep;
import com.whfc.entity.dto.Apply.rep.QueryEmpSysIdDto;
import com.whfc.fuum.entity.WxUser;
import com.whfc.fuum.service.SysUserService;
import com.whfc.wxmp.api.sys.service.WxFileUploadService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 微信文件上传服务实现类
 */
@Service
public class WxFileUploadServiceImpl implements WxFileUploadService {

    @DubboReference(interfaceClass = FileUploadInfoService.class, version = "1.0.0", timeout = 30000)
    private FileUploadInfoService fileUploadInfoService;
    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;
    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0")
    private AppEmpService appEmpService;
    @Override
    public List<FileUploadInfoRep> getAllWxFileList(Integer meetingId) {
        List<FileUploadInfoRep> allFileList;
        if ( meetingId != null){
            allFileList = fileUploadInfoService.selectFileUrlByMeetingId(meetingId);
        }else {
            allFileList = fileUploadInfoService.getAllFileList();
            if (allFileList == null || allFileList.isEmpty()) return Collections.emptyList();
            for (FileUploadInfoRep info : allFileList) {
                List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(Arrays.asList(info.getUserName()));
                for (QueryEmpSysIdDto queryEmpSysId : appEmpIds) {
                    AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysId.getAppEmpId());
                    info.setUserName(empInfo.getEmpName());
                }
            }
        }

        return allFileList;
    }

    @Override
    public Integer uploadWxFile(WxUser user, FileUploadInfo fileInfo) {
        fileInfo.setUserId(user.getId());
        int rows = fileUploadInfoService.uploadFile(fileInfo);
        return rows > 0 ? fileInfo.getId() : -1;
    }

    @Override
    public String getWxFileUrlById(Integer fileId) {
        if (fileId == null) {
            return null;
        }
        return fileUploadInfoService.getFileUrlById(fileId);
    }
}
    